package com.example.project_springboot.aop;

import com.alibaba.fastjson.JSONObject;
import com.example.project_springboot.mapper.OperateLogMapper;
import com.example.project_springboot.pojo.OperateLog;
import com.example.project_springboot.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    OperateLogMapper operateLogMapper;
    @Autowired
    HttpServletRequest httpServletRequest;

    @Around("@annotation(com.example.project_springboot.aop.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        String token = httpServletRequest.getHeader("token");

        Claims claims = JwtUtils.parseJWT(token);

        Integer operateUser = (Integer) claims.get("id");

        LocalDateTime operateTime = LocalDateTime.now();

        String className = joinPoint.getTarget().getClass().getName();

        String methodName = joinPoint.getSignature().getName();

        Object[] args = joinPoint.getArgs();

        String methodParams = Arrays.toString(args);

        long start = System.currentTimeMillis();

        Object o = joinPoint.proceed();

        String returnValue = JSONObject.toJSONString(o);

        long end = System.currentTimeMillis();

        long costTime = end - start;

        OperateLog operateLog = new OperateLog(null, operateUser, operateTime, className, methodName, methodParams, returnValue, costTime);

        operateLogMapper.insert(operateLog);
        return o;
    }
}
